package fft;
import processing.core.PApplet;
import ddf.minim.analysis.*;
import ddf.minim.spi.*;
import ddf.minim.*;
import java.io.*;
import java.math.MathContext.*;
import processing.core.PFont;
/**
 * @brief This class analyzes 2 audio samples and prints a log of the results to a file
 * @author Frequent Flyers
 */

public class FFTAnalysis {

    public Minim minim;
    public boolean DONE = false;
    /*Signal Data*/
    public double[] signal1;
    public double[] frequency;
    
    /*Minim and Processing objects we'll be using*/
    AudioPlayer m_audioPlayer;
    FFT m_fft;
    String out;
    PApplet parent; 

    FFTAnalysis(PApplet p) {
        parent = p;
    }

    /**Setup the files, load everything*/
    public void Setup(String filename, String output) {
        m_audioPlayer = minim.loadFile(filename, 2048);

        //Initialize the first FFT
        m_fft = new FFT(m_audioPlayer.bufferSize(), m_audioPlayer.sampleRate());
        System.out.println("Sample Rate: " + m_audioPlayer.sampleRate());
        m_fft.window(FFT.HANN); //Apply Spectrum window to reduce leakage
        signal1 = new double[m_fft.specSize()];
        frequency = new double[m_fft.specSize()];

        out = output;
    }

    /**Run the FFT analysis*/
    public void RunFFT() {

        System.out.println("Running FFT Analysis.");

        //Just some file house-keeping.
        File file = new File(out + ".txt");
        if (file.exists()) {
            file.delete();
        }

        //Play the file
        m_audioPlayer.play(1);

        do //While the audio is playing, run an FFT on it
        {
            m_fft.forward(m_audioPlayer.mix);
            for (int i = 0; i < m_fft.specSize(); i++) {
                double freq1 = (m_fft.getBand(i));
                frequency[i] = m_fft.indexToFreq(i);
                //System.out.println(m_fft.indexToFreq(i));
                signal1[i] = freq1;
            }

        } while (m_audioPlayer.isPlaying());

        //Output the data to a file
        for (int i = 0; i < m_fft.specSize(); i++) {
            printToFile(out, "Frequency: " + m_fft.indexToFreq(i) + " | amplitude: " + signal1[i]);
        }

        DONE = true;
    }

    /** Close resources after we've finished */
    public void Cleanup() {
        m_audioPlayer.close();
        minim.stop();
    }

    /**Print the info to the log file*/
    public void printToFile(String name, String input) {
        try {
            FileWriter write = new FileWriter(name + ".txt", true);
            PrintWriter text = new PrintWriter(write);
            text.println(input);
            text.flush();
            write.close();

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
